import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import StartGame from './game/main';
import ChatContainer from './ChatContainer';
import styles from '@/index.module.less'
import PlayerList from './PlayerList';
import { useSearchParams } from 'react-router';
import { addChatText, updatePlayersInStore } from '@/store';
import { useDispatch } from 'react-redux';
import { EventBus } from '@/EventBus';

const ballColor = Math.ceil(0xffffff * Math.random())
function randomNumY() {
  return Math.ceil(Math.random() * 750)
}

function randomNumX() {
  return Math.ceil(Math.random() * 950)
}

export default function () {
  const game = useRef<Phaser.Game | null>(null!);
  const socketRef = useRef<Socket | null>(null)
  const [searchParams] = useSearchParams()
  const nickName = searchParams.get('nickName')
  const dispatch = useDispatch()

  useEffect(() => {
    if (game.current === null) {
      game.current = StartGame("game-container");
    }
    return () => {
      if (game.current) {
        game.current.destroy(true);
        if (game.current !== null) {
          game.current = null;
        }
      }
    }
  }, [])

  useEffect(() => {
    function connect() {
      socketRef.current?.emit('registerPlayer', nickName, ballColor, randomNumX(), randomNumY())
    }
    function updatePlayers(players: any[]) {
      dispatch(updatePlayersInStore(players))
    }
    function receiveChatText({ chatText, sendId, sendTime }: any) {
      dispatch(addChatText({ chatText, sendId, sendTime }))
    }

    function toMainScene(players:any) {
      EventBus.emit('toMainScene', socketRef, players)
    }

    socketRef.current = io('ws://127.0.0.1:3000')
    socketRef.current.on('connect', connect)
    socketRef.current.on('receiveChatText', receiveChatText)
    socketRef.current.on('updatePlayers', updatePlayers)
    socketRef.current.on('toMainScene', toMainScene)

    return () => {
      socketRef.current?.off('connect', connect)
      socketRef.current?.off('receiveChatText', receiveChatText)
      socketRef.current?.off('updatePlayers', updatePlayers)
      socketRef.current?.off('toMainScene', toMainScene)
      socketRef.current?.close()
      if (socketRef.current !== null) {
        socketRef.current = null
      }
    }
  }, [])

  return (
    <>
      <div className={styles.container}>
        <ChatContainer socketRef={socketRef} />
        <div id="game-container"></div>
        <PlayerList socketRef={socketRef} />
      </div>
    </>
  )
}
